package com.nineclock.system.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.common.oss.OssProperties;
import com.nineclock.system.dto.SysCompanyDTO;
import com.nineclock.system.mapper.SysCompanyMapper;
import com.nineclock.system.pojo.SysCompany;
import com.nineclock.system.service.SysCompanyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

@Service
public class SysCompanyServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements SysCompanyService {

    /**
     * 数据回显 公司名称 logo
     *
     * @return
     */
    @Override
    public SysCompanyDTO getCompany() {
        Long companyId = CurrentUserHolder.get().getCompanyId();
        if (companyId == null) {
            throw new NcException(ResponseEnum.USER_NOT_JOIN_COMPANY);
        }
        SysCompany company = this.getById(companyId);
        if (company == null){
            throw new NcException(ResponseEnum.DATA_NOT_EXISTS);
        }
        SysCompanyDTO dto = new SysCompanyDTO();
        BeanUtils.copyProperties(company, dto);
        return dto;
    }

    /**
     * 修改公司名称与logo
     *
     * @param dto
     */
    @Override
    public void updateDto(SysCompanyDTO dto) {
        String logo = dto.getLogo();
        String name = dto.getName();
        if (dto == null || StringUtils.isBlank(logo) || StringUtils.isBlank(name)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        Long companyId = CurrentUserHolder.get().getCompanyId();
        SysCompany company = this.getById(companyId);
        if (company == null) {
            throw new NcException(ResponseEnum.DATA_NOT_EXISTS);
        }
        SysCompany sysCompany = new SysCompany();
        sysCompany.setId(companyId);
        sysCompany.setLogo(logo);
        sysCompany.setName(name);
        this.updateById(sysCompany);
    }


    @Autowired
    private OSS ossClient;

    @Autowired
    private OssProperties ossProperties;

    /**
     * logo上传
     *
     * @param multipartFile
     */
    @Override
    public String upLoadOSS(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.getSize() == 0 || multipartFile.isEmpty()) {
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }
        String type = multipartFile.getContentType();
        if (!NcConstant.ALLOWED_IMG_TYPES.contains(type)){
            throw new NcException(ResponseEnum.FILE_UPLOAD_ERROR);
        }
        if (multipartFile.getSize() > 1024 * 1024) {
            throw new NcException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }
        String originalFilename = multipartFile.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String end = originalFilename.substring(lastIndexOf);
        String nowtime = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSS").format(LocalDateTime.now());
//        String fileName = UUID.randomUUID().toString().replace("-", "") + end;
        String fileName = nowtime + end;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucketName(), fileName, inputStream);
            ossClient.putObject(putObjectRequest);
//            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
//            URL url = ossClient.generatePresignedUrl(ossProperties.getBucketName(), originalFilename, expiration);

            //拼接url地址
//            int index = ossProperties.getEndpoint().lastIndexOf("/");
//            String endpoint = ossProperties.getEndpoint().substring(index+1);
//            String logoUrl = "http://"+ossProperties.getBucketName()+"."+endpoint+"/"+fileName;

//            int indexOf = logo.lastIndexOf("?");
//            String logoUrl = logo.substring(0, indexOf);

//            Long companyId = CurrentUserHolder.get().getCompanyId();
//            SysCompany company = this.getById(companyId);
//            if (company != null) {
//                company.setLogo(logo);
//                this.updateById(company);
//            }
            String logoUrl = String.format(ossProperties.getHost(), ossProperties.getBucketName()) + fileName;
            return logoUrl;
        } catch (IOException e) {
            throw new NcException(ResponseEnum.FILE_UPLOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
